import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProFormDatePicker, ProTable } from '@ant-design/pro-components';
import { Button, DatePicker, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import type { CreateUserProps } from './components/CreateUserDrawer';
import HotProductForm from './components/HotProductForm';
import UpdateDayRateForm from './components/UpdateDayRateForm';
import { delayCommandTime, dyCpsGoodCollect, dyCpsUpdateDayRate, getStoreCate, updateProductRate } from './service';
import dayjs from 'dayjs';

const handleUpdateClue = async (selectedRows: any) => {
  // console.log(selectedRows);
  // return;
  const hide = message.loading('正在更新');
  try {
    await updateProductRate({ ...selectedRows });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [updateClueVisible, handleUpdateClueVisible] = useState<boolean>(false);
  const [currentClueRow, setCurrentClueRow] = useState<CreateUserProps>();
  const [hotProductVisible, handleHotProductVisible] = useState<boolean>(false);
  const [products, setProducts] = useState<any[]>([]);
  const [count, setCount] = useState<number>(0);
  const [amount, setAmount] = useState<number>(0);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const generateFormattedText = async (data: any[]) => {
    return data
      .map((item) => {
        return {
          text: `💥${item.productName} ${item.subRate}\n失效时间：${item.endTime}\n${item.url}\n`,
        };
      })
      .sort((a, b) => b.rate - a.rate) // 按rate从大到小排序
      .map((item) => item.text) // 提取排序后的文本
      .join('\n'); // 用换行分隔每个条目
  };
  const copyToClipboard = async (text: string) => {
    try {
      // 现代API
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
      } else {
        // 降级方案
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      console.log('复制成功');
      return true;
    } catch (err) {
      console.error('复制失败:', err);
      return false;
    }
  };
  const columns: ProColumns<any>[] = [
    {
      title: '产品店铺',
      dataIndex: 'shopName',
      copyable: true,
    },
    {
      title: '直播间',
      dataIndex: 'roomName',
      copyable: true,
    },
    {
      title: '口令',
      dataIndex: 'appLink',
      copyable: true,
    },
    {
      title: '分类',
      dataIndex: 'cate',
      valueType: 'select',
      request: async ()=>{
        const rsp = await getStoreCate();
        return rsp.data;
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueType: 'select',
      valueEnum:{
        '1': {
          text: '自动',
          status: 'Error',
        },
        "2": {
          text: '手动',
          status: 'Success',
        },
      }
    },
    {
      title: '状态',
      dataIndex: 'delay',
      valueType: 'select',
      valueEnum:{
        '1': {
          text: '已延期',
          status: 'Error',
        },
        "0": {
          text: '未延期',
          status: 'Success',
        },
      }
    },
    {
      title: '失效时间',
      dataIndex: 'endTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '后台比例',
      dataIndex: 'rate',
      hideInSearch: true,
      sorter: (a, b) => a.rate - b.rate,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount / 100).toFixed(2) + '%';
      },
    },
    {
      title: '结算比例',
      dataIndex: 'proRate',
      hideInSearch: true,
      sorter: (a, b) => a.proRate - b.proRate,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount / 100).toFixed(2) + '%';
      },
    },
    {
      title: '渠道佣金比例',
      dataIndex: 'subRate',
      hideInSearch: true,
      sorter: (a, b) => a.subRate - b.subRate,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount / 100).toFixed(2) + '%';
      },
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      sorter: (a, b) => a.orders - b.orders,
      hideInSearch: true,
    },
    {
      title: '总付款金额',
      dataIndex: 'amount',
      hideInSearch: true,
      sorter: (a, b) => a.amount - b.amount,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount / 100).toFixed(2);
      },
    },
    {
      title: '预估佣金',
      dataIndex: 'commission',
      hideInSearch: true,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount / 100).toFixed(2);
      },
    },
    {
      title: '订单时间',
      dataIndex: 'dates',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '订单时间',
      dataIndex: 'date',
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '失效时间',
      dataIndex: 'invalidDate',
      valueType: 'date',
      hideInTable: true,
      copyable: true,
    },
   {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 80,
      align: 'right',
      render: (text, record) =>{  
        return  [
          <a
            key="follow"
            onClick={async () => {
             handleUpdateClueVisible(true);
             setCurrentClueRow(record);
            }}
          >
            编辑
          </a> ,
          record.delay === "0" ? 
          <a
            key="delay"
            onClick={async () => {
             Modal.confirm({
                content: '是否延期当前口令',
                onOk: async () => {
                  const rsp = await delayCommandTime({command: record.appLink});
                  if(rsp.code === "SUCCESS") {
                    message.open({
                      type: 'success',
                      content: '提交成功'
                    })
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  } 
                },
              })
            }}
          >
            延期
          </a> : ''
        ]
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部店铺-总支付金额：' + count + '&&总佣金：' + amount}
        actionRef={actionRef}
        rowClassName={(record: any) => {
          if (record.proRate === 0 && record.amount !== 0) {
            return 'completed-row'; // 为状态为“已完成”的行添加样式
          }
          return '';
        }}
        rowKey="key"
        toolBarRender={() => [
         
          <Button
            key="23"
            type="primary"
            onClick={() => {
              handleHotProductVisible(true);
            }}
          >
            热品合集
          </Button>,
        ]}
        search={{
          defaultCollapsed: false,
         
        }}
        request={async (params: any) => {
          const rsp = await dyCpsGoodCollect(params);
          if (rsp.code === 'SUCCESS') {
            setCount(rsp.data.count);
            setAmount(rsp.data.amount);
            setProducts(rsp.data.list);
            console.log(JSON.stringify(rsp.data.list));
            return {
              data: rsp.data.list,
              total: rsp.data.total,
            };
          }
        }}
        columns={columns}
      />
      <UpdateDayRateForm
        onSubmit={async (value) => {
          // return;
          const success = await handleUpdateClue({ ...value });
          if (success) {
            handleUpdateClueVisible(false);
            setCurrentClueRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateClueVisible(false);
          setCurrentClueRow(undefined);
        }}
        updateModalVisible={updateClueVisible}
        values={currentClueRow || {}}
        formType={0}
      />
      <HotProductForm
        visible={hotProductVisible}
        onSubmit={async (value) => {
          // return;
          if (value.length === 0) {
            message.error('请生成热品合集');
            return;
          } else {
            const formattedText = await generateFormattedText(value);
            const title = `🎉🎉 热门推荐榜单合集 🎉🎉\n`;
            copyToClipboard(title + formattedText).then((success) => {
              if (success) {
                message.success('复制成功！');
              } else {
                message.error('复制失败，请手动复制');
              }
            });
          }
        }}
        onCancel={() => {
          handleHotProductVisible(false);
        }}
        values={{ hotCount: 10, channel: 'CPS-ZBJ-yf2', products: products }} // 初始值
      />
    </PageContainer>
  );
};
export default TableList;
